package com.damai.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;

import org.beetl.core.Configuration;
import org.beetl.core.GroupTemplate;
import org.beetl.core.ResourceLoader;
import org.beetl.core.Template;
import org.beetl.core.resource.ClasspathResourceLoader;
import org.beetl.core.resource.StringTemplateResourceLoader;
import org.beetl.core.resource.WebAppResourceLoader;

import com.citywithincity.utils.IoUtil;
import com.citywithincity.utils.PathUtil;

public class ViewUtil {
	public static GroupTemplate resTemplate;
	public static GroupTemplate fileTemplate;
	public static GroupTemplate stringTemplate;
	static{
		try{
			File path = PathUtil.getWebInfPath("");
			ResourceLoader resourceLoader = new WebAppResourceLoader(path.getAbsolutePath());
			Configuration cfg = Configuration.defaultConfiguration();
			
			fileTemplate = new GroupTemplate(resourceLoader, cfg);
			
			
			cfg = Configuration.defaultConfiguration();
			resourceLoader = new ClasspathResourceLoader(ViewUtil.class.getClassLoader());
			resTemplate = new GroupTemplate(resourceLoader, cfg);
			
			resourceLoader = new StringTemplateResourceLoader();
			stringTemplate = new GroupTemplate(resourceLoader,cfg);
			
			
			
		}catch(IOException e){
			throw new RuntimeException(e);
		}
	}
	
	public static GroupTemplate createGroupTemplate(String config) throws IOException{
		Properties p = new Properties();
		p.load(PathUtil.getInputStream(ViewUtil.class, config));
		Configuration cfg = new Configuration(p);
		StringTemplateResourceLoader resourceLoader = new StringTemplateResourceLoader();
		return new GroupTemplate(resourceLoader, cfg);
	}
	
	
	
	public static String render(GroupTemplate template, String key,Map<String, Object> data){
		Template t = template.getTemplate(key);
		t.binding(data);
		return t.render();
	}
	public static String readContent(String src) throws IOException{
		BufferedReader reader =null;
		try{
			reader = new BufferedReader(new FileReader(src));
			StringBuilder sb = new StringBuilder();
			String line = null;
			while((line=reader.readLine())!=null){
				sb.append(line);
				sb.append("\r\n");
			}
			return sb.toString();
		}finally{
			IoUtil.close(reader);
		}
		
	}
	public static String renderOutFile(String file, Map<String, Object> data) throws IOException {
		
		return render(stringTemplate, readContent(file), data);
	}

	
	public static String renderFile(String key, Map<String, Object> data) {
		return render(fileTemplate, key, data);
	}

	public static String renderRes(String key, Map<String, Object> data) {
		return render(resTemplate, key, data);
	}
}
